package main

import (
	"fmt"
	"math"
)

func main() {
	matrix := [][]int{
		{1, 2, 3, 4},
		{5, 6, 7, 8},
		{9, 10, 11, 12},
	}
	fmt.Println(SpiralMatrix(matrix))
}

/**
 * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
 *
 * @param matrix int整型二维数组
 * @return int整型一维数组
 */
func SpiralMatrix(matrix [][]int) []int {
	// write code here
	if len(matrix) == 1 {
		return matrix[0]
	}
	I, J := len(matrix), len(matrix[0])
	N := I * J
	res := make([]int, 0, N)
	way := [][]int{
		{0, 1},
		{1, 0},
		{0, -1},
		{-1, 0},
	}

	index := 0
	i, j := 0, 0
	for len(res) < N {
		for i >= 0 && i < I && j >= 0 && j < J && matrix[i][j] != math.MinInt32 {
			res = append(res, matrix[i][j])
			matrix[i][j] = math.MinInt32
			i += way[index][0]
			j += way[index][1]
		}
		i -= way[index][0]
		j -= way[index][1]
		index = (index + 1) % 4
		i += way[index][0]
		j += way[index][1]
	}

	return res
}
